<?php

namespace app\modules\cruise\controllers;

use Yii;
use app\modules\cruise\models\RoomUse;
use app\modules\cruise\models\RoomUseSearch;
use app\modules\cruise\models\Excel2;
use app\modules\cruise\models\Room;
use app\modules\cruise\models\Customer;
use app\modules\cruise\models\CustomerCheck;
use yii\web\UploadedFile;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * RoomUseController implements the CRUD actions for RoomUse model.
 */
class RoomUseController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
             'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        //'actions' => ['list', 'index','create','view','update','delete'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all RoomUse models.
     * @return mixed
     */
    public function actionIndex()
    {
        
        $searchModel = new RoomUseSearch();
        $dataProvider = $searchModel->search_2(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single RoomUse model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new RoomUse model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new RoomUse();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }else{
            $model->status = 1;
            $model->download = 0;
            return $this->render('create', [
            'model' => $model,
            ]);
        }

        
    }

    /**
     * Updates an existing RoomUse model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing RoomUse model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the RoomUse model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return RoomUse the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = RoomUse::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }


    //下载列表
    public function actionDownList($cruise_id){

        if(empty($cruise_id)){
            return false;
        }

        return $this->render('download', [
            'cruise_id' => $cruise_id
        ]); 

    }

    //获得房间列表
    public function actionGetList(){
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $data = \yii::$app->request->get();
       
        $pageNum = isset($data['pageNum']) ? $data['pageNum'] : 1;
        
        $download = isset($data['download']) ? $data['download'] : 0;
        $code = isset($data['code']) ? $data['code'] : 0;

        $pageSize = 20;
        $data = [];
        $query = RoomUse::find()->where(['status'=>1]);
        if($download >= 0){
            $query->andWhere(['download'=>$download]);
        }else if($download < 0){
            $query->andWhere(['<=','download',1]);
        } 

        if($code){
            $query->andWhere(['like', 'code', $code]);
        }

        $totalItem = $query->count();
        $totalPage = ceil($totalItem/$pageSize);
        $startItem = ($pageNum-1) * $pageSize;
        $res['totalItem'] = $totalItem;
        $res['pageSize'] = $pageSize;
        $res['totalPage'] = $totalPage;
        $model = $query->offset($startItem)->limit($pageSize)->all();

        if($model){
            foreach($model as $key=>$or){
                $data[$key]['id'] = $or->id;
                $data[$key]['name'] = $or->room->name.' '.$or->room->code.' '.$or->num .'人间';
                $data[$key]['code'] = $or->code ? $or->code : '';
                $data[$key]['download'] = $or->download;
                $dataCustomer = [];
                $customers = $or->customer;
                if($customers){
                    foreach($customers as $k2 => $c){
                        if($c->status == 1){
                            $dataCustomer[$k2]['id'] = $c->id;
                            $dataCustomer[$k2]['name'] = $c->first_name.$c->last_name;
                        }   
                        
                    }   
                }
                $data[$key]['download'] = \yii::$app->params['download'][$or->download];
                $data[$key]['customers'] = $dataCustomer;  

            }
        }
        $res['data_content'] = $data;
        return $res;

    }

    //下载房间列表
    public function actionExcel(){
        $data = yii::$app->request->post();

        $excel2 = new Excel2();
        $res = ['status' => 0 ,'msg'=> '' , 'data'=>''];
        if(empty($data)){
            print_r(json_encode($res));
            exit();
        }
        $template_id = isset($data['template_id']) ? $data['template_id'] : '';
        $cruise_id = isset($data['cruise_id']) ? $data['cruise_id'] : '';
        $room = isset($data['room']) ? $data['room'] : '';

        $files = ['status'=>1,'msg'=>'','data'=>''];
        if($template_id == 3){
            $files['data'] = $excel2->Template3($cruise_id,$room);
            print_r(json_encode($files));
            exit();
        }else if($template_id == 4){
            $files['data'] = $excel2->Template4($cruise_id,$room);
            print_r(json_encode($files));
            exit();
        }else if($template_id == 5){
            $files['data'] = $excel2->Template5($cruise_id,$room);
            print_r(json_encode($files));
            exit();
        }else if($template_id == 6){
            $files['data'] = $excel2->Template6($cruise_id,$room);
            print_r(json_encode($files));
            exit();
        }else if($template_id == 8){
            $files['data'] = $excel2->Template8($cruise_id,$room);
            print_r(json_encode($files));
            exit();
        }else if($template_id == 9){
            $files['data'] = $excel2->Template9($cruise_id,$room);
            print_r(json_encode($files));
            exit();
        }
        print_r(json_encode($res));

    }

     //下载Excel文件
    public function actionDownloadFile($name,$url){
        $url = iconv("utf-8","gb2312",$url); 
        if(file_exists($url)){
            header("Content-type: application/octet-stream");    
            header("Accept-Ranges: bytes");    
            header("Accept-Length: " . filesize($url));    
            header("Content-Disposition: attachment; filename=" .$name);    
            @readfile($url);
        }else{
            return false;
        }       

    }       



    //导入人员信息
    public function actionImportCut(){
        // header("Content-type:text/html; charset=utf-8");
        // $path = sprintf('%s/web/cut.xlsx', Yii::$app->basePath);
        $path = $this->upload_excel();

        $data = $this->getData($path);
        $room_arr = [];
        $data_arr = [];
        //var_dump($data);exit();
        if($data['room']){
            foreach($data['room'] as $key=>$val){
                $room_arr[$val][] = $key;
            }
        }
        
        if($data['data']){
            $data_arr = $data['data'];
        }
       
        $gender_en = [
            '男' => 1,
            '女' => 2,
        ];
        $province_2 = \yii::$app->params['area']['country_code_3']; //三字码
        $province_2 = array_flip($province_2);
        //导入数据
        $transaction = Yii::$app->db->beginTransaction();
        try{

            foreach($room_arr as $varr){
                $num = count($varr);
                //获取房型
                $type = isset($data_arr[$varr[0]]) ? $data_arr[$varr[0]]['D'] : '';
                //房间序号
                $room_ord = isset($data_arr[$varr[0]]) ? $data_arr[$varr[0]]['E'] : '';
                //房间备注
                $room_remark = isset($data_arr[$varr[0]]) ? $data_arr[$varr[0]]['G'] : '';
                //获取ROOM_ID
                $room = Room::find()->where(['code'=>$type])->one();
                if($room){
                    //创建房间
                    $room_use = new RoomUse();
                    $room_use->room_id = $room->id;
                    $room_use->num = $num;
                    $room_use->remark = $room_remark;
                    $room_use->ord = $room_ord;

                    if($room_use->save()){
                        foreach($varr as $kvarr){
                            $customer = new Customer();
                            $customer->room_use_id = $room_use->id;
                            $customer->room_id = $room_use->room_id;

                            if($this->ischinese($data_arr[$kvarr]['I']) == 1){
                                $name = $this->splitName($data_arr[$kvarr]['I']);
                                $customer->first_name = $name[0];
                                $customer->last_name = $name[1];
                            }else{
                                $customer->first_name = $data_arr[$kvarr]['J'];
                                $customer->last_name = $data_arr[$kvarr]['K'];
                            }
                            

                            $customer->en_first_name = $data_arr[$kvarr]['J'];
                            $customer->en_last_name = $data_arr[$kvarr]['K'];

                            $customer->gender = isset($gender_en[$data_arr[$kvarr]['L']]) ?$gender_en[$data_arr[$kvarr]['L']] : 1;
                            $customer->country = isset($province_2[$data_arr[$kvarr]['M']]) ? $province_2[$data_arr[$kvarr]['M']] : $data_arr[$kvarr]['M'];

                            $customer->birthday = $data_arr[$kvarr]['N'];

                            $customer->native = $data_arr[$kvarr]['O'];
                            $customer->passport = $data_arr[$kvarr]['P'];
                            $customer->passport_add = $data_arr[$kvarr]['Q'];
                            $customer->passport_grant = $data_arr[$kvarr]['R'];
                            $customer->passport_date = $data_arr[$kvarr]['S']; 

                          
                            $customer->phone = $data_arr[$kvarr]['T'];//手机号

                         
                            $customer->size = $data_arr[$kvarr]['U'];
                            $customer->color = $data_arr[$kvarr]['V'];

                            $customer->remark = $data_arr[$kvarr]['H'];//备注
                         
                            $customer->ticket = $data_arr[$kvarr]['W'];

                            $customer->group = $data_arr[$kvarr]['B'];
                            $customer->supply = $data_arr[$kvarr]['C'];
        
                            $customer->cancel = 1;
                            $customer->passport_type = 1;
                            $customer->nation = '汉';
                            if($customer->save()){

                            }else{
                               $transaction->rollBack();
                               print_r($customer->errors);
                               print_r(json_encode(['code'=>'error','message'=>'导入失败1']));
                                exit();  
                            }
                        }
                    }else{
                        $transaction->rollBack();
                        print_r($room_use->errors);
                        print_r(json_encode(['code'=>'error','message'=>'导入失败2']));
                        exit();
                    }

                }else{
                    $transaction->rollBack();
                    print_r(json_encode(['code'=>'error','message'=>'有不存在的房型']));
                    exit();
                }
            }

            $transaction->commit();
            
        }catch(\Exception $e){
            $transaction->rollBack();
            throw $e;
        }

        print_r(json_encode(['code'=>'ok','message'=>'导入成功!']));
       
    }

    //判断是英文
    private function ischinese($str){

        $pattern = '/[^\x00-\x80]/'; 
        if(preg_match($pattern,$str)){ 
            return 1;
        }else{ 
            return 0; 
        } 
    }

    /** 
     * 把全名拆分为姓氏和名字 
     * @param string $fullname 全名 
     * @return array 一维数组,元素一是姓,元素二为名 
     */
    private function splitName($fullname){  
         $hyphenated = array('欧阳','太史','端木','上官','司马','东方','独孤','南宫','万俟','闻人','夏侯','诸葛','尉迟','公羊','赫连','澹台','皇甫',  
            '宗政','濮阳','公冶','太叔','申屠','公孙','慕容','仲孙','钟离','长孙','宇文','城池','司徒','鲜于','司空','汝嫣','闾丘','子车','亓官',  
            '司寇','巫马','公西','颛孙','壤驷','公良','漆雕','乐正','宰父','谷梁','拓跋','夹谷','轩辕','令狐','段干','百里','呼延','东郭','南门',  
            '羊舌','微生','公户','公玉','公仪','梁丘','公仲','公上','公门','公山','公坚','左丘','公伯','西门','公祖','第五','公乘','贯丘','公皙',  
            '南荣','东里','东宫','仲长','子书','子桑','即墨','达奚','褚师');  
            $vLength = mb_strlen($fullname, 'utf-8');  
            $lastname = '';  
            $firstname = '';//前为姓,后为名  
            if($vLength > 2){  
                $preTwoWords = mb_substr($fullname, 0, 2, 'utf-8');//取命名的前两个字,看是否在复姓库中  
                if(in_array($preTwoWords, $hyphenated)){  
                    $lastname = $preTwoWords;  
                    $firstname = mb_substr($fullname, 2, 10, 'utf-8');  
                }else{  
                    $lastname = mb_substr($fullname, 0, 1, 'utf-8');  
                    $firstname = mb_substr($fullname, 1, 10, 'utf-8');  
                }  
            }else if($vLength == 2){//全名只有两个字时,以前一个为姓,后一下为名  
                $lastname = mb_substr($fullname ,0, 1, 'utf-8');  
                $firstname = mb_substr($fullname, 1, 10, 'utf-8');  
            }else{  
                $lastname = $fullname;  
            }  
            return array($lastname, $firstname);  
    }

    //上传文件
    private function upload_excel(){

        $upload = UploadedFile::getInstanceByName('excel');
        if($upload){
            $suffix = $upload->extension;
            $dir = sprintf("uploads/excel/%s", date("Ym"));
             
            if(!is_readable($dir)) {
                is_file($dir) or mkdir($dir,0755);  
            }  

            $path = sprintf('%s/%s.%s', $dir, uniqid(true), $suffix);

            if($upload->saveAs($path)){
                return $path;
            }
        }else{
            return false;
        }

    }


    //获取excel 数据
    private function getData($filePath){//{{{
        if(empty($filePath)){
            return [];
        }
        $PHPReader = new \PHPExcel_Reader_Excel2007();

        if(!$PHPReader->canRead($filePath)){
            $PHPReader = new \PHPExcel_Reader_Excel5();
        }

        if(!$PHPReader->canRead($filePath)){
            return ;
        }

        $PHPExcel = $PHPReader->load($filePath);

        $currentSheet = $PHPExcel->getSheet(0);

        $allRow = $currentSheet->getHighestRow();
  
        $arrExcel = []; //数据
        $roomExcel = []; //房间序号
    
        for($rowIndex = 2;$rowIndex <= $allRow; $rowIndex++){
            $a2 = 'F'.$rowIndex;
            $c2 = $currentSheet->getCell($a2)->getValue(); 
            if($c2 instanceof PHPExcel_RichText){     //富文本转换字符串
                $c2 = $c2->__toString();
            }
            if(!empty($c2)){
                $roomExcel[$a2] = strtoupper(trim($c2));
            }
            for($colIndex='A';$colIndex<='W';$colIndex++){
                $addr = $colIndex.$rowIndex;
                
                if($colIndex == 'N' || $colIndex == 'R' || $colIndex == 'S'){
                    if($currentSheet->getCell($addr)->getValue()){
                        $cell = gmdate('Y-m-d',\PHPExcel_Shared_Date::ExcelToPHP($currentSheet->getCell($addr)->getValue()));
                    }else{
                        $cell = '';
                    }  
                }else{
                    $cell = $currentSheet->getCell($addr)->getValue();
                }
                
                if($cell instanceof PHPExcel_RichText){     //富文本转换字符串
                    $cell = $cell->__toString();
                }
                if(!empty($cell)){
                    $arrExcel['F'.$rowIndex][$colIndex]= trim($cell);
                }else{
                    $arrExcel['F'.$rowIndex][$colIndex]= '';
                }
                $cell = '';
            }

        }
      
        $data['data'] = $arrExcel; //数据
        $data['room'] = $roomExcel; //房间序号

        return $data;

    }//}}}








}
